//
//  HLReportViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/18.
//

#import "HLReportViewController.h"
#import "HLPickerManager.h"
#import "HLOSSManager.h"
#import "HLReportRequest.h"

#import "HLImageStatusView.h"

@interface HLReportViewController ()<QMUITextViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *contentTipLabel;
@property (nonatomic, strong) QMUITextView *textView;
@property (nonatomic, strong) UILabel *textCountLabel;
@property (nonatomic, strong) UILabel *imageTipLabel;
@property (nonatomic, strong) QMUIFloatLayoutView *imagesView;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) QMUIFloatLayoutView *labelsView;
@property (nonatomic, strong) QMUIButton *startButton;
@property (nonatomic, assign) HLReportType type;
@property (nonatomic, strong) NSArray *reasonList;
@property (nonatomic, strong) HLReportModel *currentReason;
@property (nonatomic, strong) NSString *maleClient;
@property (nonatomic, strong) NSString *userId;
@property (nonatomic, strong) HLPickerManager *pickerManager;
@property (nonatomic, strong) HLOSSManager *ossManager;
@property (nonatomic, strong) NSMutableArray <HXPhotoModel *> * photos;
@property (nonatomic, strong) NSMutableArray <UIImage *> *imagesArray;

@end

@implementation HLReportViewController

- (instancetype)initWithType:(HLReportType)type userId:(NSString *)userId
{
    self = [super init];
    if (self){
        self.type = type;
        self.userId = userId;
        self.imagesArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pickerManager = [[HLPickerManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto avatar:NO];
    [self.pickerManager updateMaxNum:3 photos:[self.photos copy]];
    self.ossManager = [[HLOSSManager alloc] initWithOSSPath:@"report"];
    
    self.request = [[HLReportRequest alloc] initWithReason];
    self.request.delegate = self;
    [self requestInit];
}

- (void)requestInit
{
    [self showEmptyView];
    [self.emptyView.loadingView startAnimating];
    [self.emptyView setTextLabelText:@"加载中..."];
    [self.request start];
}


- (void)setupNavigationItems
{
    [super setupNavigationItems];
    self.title = @"举报";
}


- (void)initSubviews
{
    [super initSubviews];
    self.scrollView = [[UIScrollView alloc] init];
    [self.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(self.view);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 76));
    }];
    
    self.contentView = [[UIView alloc] init];
    [self.scrollView addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    self.contentTipLabel = [[UILabel alloc] init];
    _contentTipLabel.font = UIFontMake(15);
    _contentTipLabel.textColor = HLTextColor1;
    _contentTipLabel.text = @"具体情况说明";
    _contentTipLabel.numberOfLines = 0;
    [_contentView addSubview:_contentTipLabel];
    [_contentTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.top.mas_equalTo(NavigationContentTopConstant + 18);
    }];
    
//    [HLUIHelper showRequiredLabelWithView:_contentTipLabel];
    
    self.textView = [[QMUITextView alloc] init];
    _textView.placeholder = @"请描述举报内容，以便我们快速核实。（必填）";
    _textView.font = UIFontMake(14);
    _textView.textColor = HLTextColor1;
    _textView.contentInset = UIEdgeInsetsMake(12, 12, 12, 12);
    _textView.backgroundColor = HLBackgroundColor;
    _textView.maximumTextLength = 100;
    _textView.delegate = self;
    _textView.layer.masksToBounds = YES;
    _textView.layer.cornerRadius = 4;
    [_contentView addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.top.equalTo(_contentTipLabel.mas_bottom).offset(18);
        make.height.mas_equalTo(136);
    }];
    
    
    self.textCountLabel = [[UILabel alloc] init];
    _textCountLabel.font = UIFontMake(12);
    _textCountLabel.textColor = HLTextColor2;
    _textCountLabel.text = @"0/100";
    [_contentView addSubview:_textCountLabel];
    [_textCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(_textView).offset(-12);
    }];

    self.imageTipLabel = [[UILabel alloc] init];
    _imageTipLabel.font = UIFontMake(15);
    _imageTipLabel.textColor = HLTextColor1;
    _imageTipLabel.text = @"图片（0/3）选填";
    [_contentView addSubview:_imageTipLabel];
    [_imageTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.top.equalTo(_textView.mas_bottom).offset(20);
    }];

    self.imagesView = [[QMUIFloatLayoutView alloc] init];
    _imagesView.padding = UIEdgeInsetsMake(6, 6, 6, 6);
    _imagesView.itemMargins = UIEdgeInsetsMake(0, 1, 0, 1);
    _imagesView.minimumItemSize = CGSizeMake(102, 102);// 以2个字的按钮作为最小宽度
    _imagesView.maximumItemSize = CGSizeMake(102, 102);
    [self.contentView addSubview:_imagesView];
    [_imagesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(120);
        make.top.equalTo(_imageTipLabel.mas_bottom).offset(12);
    }];
    
    QMUIButton *uploadButton = [[QMUIButton alloc] init];
    [uploadButton setImage:UIImageMake(@"edit_cell_image") forState:UIControlStateNormal];
    [uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
    [uploadButton setBackgroundColor:HLBackgroundColor];
    uploadButton.cornerRadius = 4;
    [_imagesView addSubview:uploadButton];
    
    self.tipLabel = [[UILabel alloc] init];
    _tipLabel.font = UIFontMake(15);
    _tipLabel.textColor = HLTextColor1;
    _tipLabel.text = @"问题类型";
    _tipLabel.numberOfLines = 0;
    [_contentView addSubview:_tipLabel];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.bottom.equalTo(_imagesView.mas_bottom).offset(20);
       
    }];
//    [HLUIHelper showRequiredLabelWithView:_tipLabel];
    
    self.labelsView = [[QMUIFloatLayoutView alloc] init];
    _labelsView.padding = UIEdgeInsetsMake(6, 6, 6, 6);
    _labelsView.itemMargins = UIEdgeInsetsMake(6, 6, 6, 6);
    _labelsView.minimumItemSize = CGSizeMake(88, 36);// 以2个字的按钮作为最小宽度
    [self.contentView addSubview:_labelsView];
    [_labelsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tipLabel.mas_bottom).offset(18);
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(218);
    }];



    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_labelsView.mas_bottom).offset(96);
    }];

    
    self.startButton = [[QMUIButton alloc] init];
    [_startButton setTitle:@"提交" forState:UIControlStateNormal];
    [_startButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_startButton.titleLabel setFont:UIFontMake(16)];
    [_startButton setBackgroundColor:HLMainColor];
    _startButton.cornerRadius = 4;
    [_startButton addTarget:self action:@selector(reportAction) forControlEvents:UIControlEventTouchUpInside];
    _startButton.enabled = NO;
    [self.view addSubview:_startButton];
    [_startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(52);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 24));
    }];
    
}

- (void)updateLabels
{
    NSInteger tagIndex = 0;
    for (HLReportModel *reason in self.reasonList) {
        QMUIButton *labelButton = [[QMUIButton alloc] init];
        [labelButton setTitle:reason.reportClassName forState:UIControlStateNormal];
        [labelButton setTitleColor:HLTextColor3 forState:UIControlStateNormal];
        [labelButton.titleLabel setFont:UIFontMake(14)];
        labelButton.layer.masksToBounds = YES;
        labelButton.layer.cornerRadius = 16;
        labelButton.backgroundColor = HLBackgroundColor;
        labelButton.contentEdgeInsets = UIEdgeInsetsMake(2, 16, 2, 16);
        labelButton.tag = tagIndex;
        [labelButton addTarget:self action:@selector(labelAction:) forControlEvents:UIControlEventTouchUpInside];
        [_labelsView addSubview:labelButton];
        
        tagIndex += 1;
    }
}

- (void)labelAction:(QMUIButton *)labelButton
{
    [_labelsView.subviews enumerateObjectsUsingBlock:^(__kindof QMUIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj setBackgroundColor:HLBackgroundColor];
        [obj setTitleColor:HLTextColor3 forState:UIControlStateNormal];
    }];
    [labelButton setBackgroundColor:[HLMainColor colorWithAlphaComponent:0.2]];
    [labelButton setTitleColor:HLMainColor forState:UIControlStateNormal];
    self.currentReason = self.reasonList[labelButton.tag];
    if (self.currentReason && (self.textView.text.length > 0)){
        self.startButton.enabled = YES;
    }
}

- (void)updateWithPhoto:(NSArray<HXPhotoModel *> *)models
{
    [_imagesView qmui_removeAllSubviews];
    [_imagesArray removeAllObjects];
    self.photos = [NSMutableArray arrayWithArray:models];
    [self.pickerManager updateMaxNum:3 photos:models];
    _imageTipLabel.text = [NSString stringWithFormat: @"图片（%ld/3）选填", models.count];
    if (models.count > 0){
        MJWeakSelf;
        for (HXPhotoModel *m in models) {
            [m getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                
                [weakSelf.imagesArray addObject:image];
                
                HLImageStatusView *imageButton = [[HLImageStatusView alloc] init];
                [imageButton.imageView setContentMode:UIViewContentModeScaleAspectFill];
                [imageButton.imageView setImage:image];
                imageButton.statusLabel.hidden = YES;
                [imageButton.closeButton addTarget:self action:@selector(delAction:) forControlEvents:UIControlEventTouchUpInside];
                [imageButton setBackgroundColor:HLBackgroundColor];
                imageButton.layer.cornerRadius = 4;
                imageButton.closeButton.tag = [models indexOfObject:m];
                [weakSelf.imagesView addSubview:imageButton];
                if (models.count < 3 && weakSelf.imagesView.subviews.count == models.count){
                    QMUIButton *uploadButton = [[QMUIButton alloc] init];
                    [uploadButton setImage:UIImageMake(@"edit_cell_image") forState:UIControlStateNormal];
                    [uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
                    [uploadButton setBackgroundColor:HLBackgroundColor];
                    uploadButton.cornerRadius = 4;
                    [weakSelf.imagesView addSubview:uploadButton];
                }
                
            } failed:nil];
        }
    } else {
        if (models.count < 3 && self.imagesView.subviews.count == models.count){
            QMUIButton *uploadButton = [[QMUIButton alloc] init];
            [uploadButton setImage:UIImageMake(@"edit_cell_image") forState:UIControlStateNormal];
            [uploadButton addTarget:self action:@selector(uploadAction) forControlEvents:UIControlEventTouchUpInside];
            [uploadButton setBackgroundColor:HLBackgroundColor];
            uploadButton.cornerRadius = 4;
            [self.imagesView addSubview:uploadButton];
        }
    }
    
    
    
}

- (void)delAction:(UIButton *)btn
{
    [self.photos removeObjectAtIndex:btn.tag];
    [self updateWithPhoto:self.photos];
}

- (void)uploadAction
{
    MJWeakSelf;
    [self.pickerManager showWithController:self block:^(NSArray<HXPhotoModel *> * datas) {
        [weakSelf updateWithPhoto:datas];
    }];
}

- (void)reportAction
{
    if (!self.currentReason){
        [QMUITips showWithText:@"请选择举报理由"];
        return;
    }
    
    if (self.textView.text.length == 0){
        [QMUITips showWithText:@"请填写描述举报内容"];
        return;
    }
    
    if (self.imagesArray.count > 0){
       
        MJWeakSelf;
        [self.ossManager uploadDatas:[self.imagesArray copy] callBack:^(NSArray<NSString *> *urls) {
            [weakSelf reportRequestWithImageUrls:urls];
        }];
    } else {
        [self reportRequestWithImageUrls:@[]];
    }
    

}

- (void)reportRequestWithImageUrls:(NSArray *)imageUrls
{
    NSDictionary *params = @{
        @"reportClassCode": self.currentReason.reportClassCode,
        @"reportClassName": self.currentReason.reportClassName,
        @"reportContent": self.textView.text,
        @"reportType": @(self.type),
        @"reportUserId":_userId,
        @"userReportOpus": imageUrls,
    };
    HLReportRequest *reportRequest = [[HLReportRequest alloc] initWithParams:params];
    reportRequest.delegate = self;
    [reportRequest start];
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:UIColorWhite];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorBlack;
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view
{
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDarkContent;
}


- (void)requestFinished:(__kindof YTKBaseRequest *)request
{
    [super requestFinished:request];
    
    HLReportRequest *reportRequest = (HLReportRequest *)request;
    
    if ([reportRequest isReport]){
        [QMUITips showWithText:@"我已收到您的举报，我们将尽快核实。感谢您"];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        if (reportRequest.reasonList.count == 0){
            [self.emptyView setLoadingViewHidden:YES];
            [self.emptyView setImage:UIImageMake(@"empty_icon_7")];
            [self.emptyView setTextLabelText:reportRequest.message];
        } else {
            [self hideEmptyView];
            self.reasonList = reportRequest.reasonList;
            [self updateLabels];
        }
    }
    
}

- (void)requestFailed:(__kindof HLReportRequest *)request
{
    [super requestFailed:request];
}

#pragma QMUITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    self.textCountLabel.text = [NSString stringWithFormat:@"%ld/100", textView.text.length];
    if (self.currentReason && (textView.text.length > 0)){
        self.startButton.enabled = YES;
    }
}
@end
